/*
   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package com.zavakid.scala.exercise.chapter13

import scala.collection.mutable.LinkedList

/**
 * @author zavakid 2013-6-12 下午1:56:11
 * @since 1.0
 */
object Main13 {

  def no1(s: String) = {
    val map = scala.collection.mutable.Map[Char, scala.collection.mutable.SortedSet[Int]]()
    s.zipWithIndex.foreach {
      case (c: Char, i: Int) => {
        if (map.contains(c)) map(c) + i
        else map(c) = scala.collection.mutable.SortedSet[Int](i)
      }
    }
    map
  }

  def no2(s: String) = {
    s.zipWithIndex.groupBy(_._1).mapValues {
      _.map(_._2).toSet
    }
  }

  def no3(list: LinkedList[Int]): LinkedList[Int] = {
    list.dropWhile(_ == 0)
  }

  def no4(set: Set[String], map: Map[String, Int]): Set[Int] = {
    val result = scala.collection.mutable.SortedSet[Int]()
    set.flatMap(map.get(_))
  }

  def no5(s: Seq[String]): String = {
    s.reduce(_ + _)
  }

  def no6(list: List[Any]): List[Any] = {
    (list :\ List[Any]()) {
      (el, lst) =>
        lst :+ el
    }
  }

  def no7(prices: Seq[Int], quantities: Seq[Int]): Seq[Int] = {
    (prices zip quantities).map(Function.tupled(_ * _))
  }

  def no8(array: Array[Double], n: Int): Array[Array[Double]] = {
    array.grouped(n).toArray
  }

  //no9 并发问题 frequencies.getOrElse(c,0) + 1 不是原子的
  // 还有有错误，刚刚的问题根本没有解决，主要是在 +1 的时候会有并发

  //把共享变量放到不同的线程中，而且还不加锁...
  def no10(str: String): Map[Char, Int] = {
    str.par.aggregate(Map[Char, Int]())({
      (map, el) =>
        map + (el -> (map.getOrElse(el, 0) + 1))
    }, {
      (map_a, map_b) =>
        (map_a.keySet ++ map_b.keySet).foldLeft(Map[Char, Int]()) {
          (map, el) =>
            map + (el -> (map_a.getOrElse(el, 0) + map_b.getOrElse(el, 0)))
        }
    })
  }
}